import json

from django_redis import get_redis_connection

from utils.cookiesecret import CookieSecret


def merge_cart_cookie_to_redis(request, response):
    #cookie覆盖redis的数据信息
    cookie_str =request.COOKIES.get('carts')
    #读取cookie数据
    #redis连接
    redis_client = get_redis_connection('carts')

    if cookie_str:
        cookie_cart_dict = CookieSecret.loads(cookie_str)
    #cookie存在,redis也存在的  覆盖  for 遍历
        for sku_id in cookie_cart_dict:
            sku_dict = cookie_cart_dict[sku_id]
            redis_client.hset(request.user.id,sku_id,json.dumps(sku_dict))
    #删除cookie
        response.delete_cookie('carts')